import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC } from './global.auth';
import { JwtService } from '@nestjs/jwt';
import config from '../../../config';

@Injectable()
export class AuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const reflect = new Reflector();
    const isPublic = reflect.getAllAndOverride<boolean>(IS_PUBLIC, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const request: any = context.switchToHttp().getRequest();
    // console.log(request.headers.authorization);
    // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
    const token = this.validateToken(request);
    // console.log(token);
    if (!token) {
      throw new HttpException(
        {
          msg: '没有授权访问，请先登陆',
        },
        HttpStatus.UNAUTHORIZED,
      );
    }

    try {
      const jwtService = new JwtService();
      const payload = await jwtService.signAsync(token, {
        secret: config.jwt,
      });
      // console.log(payload);
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      request.user = payload;
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      throw new HttpException(
        {
          msg: '没有授权访问，请先登陆',
        },
        HttpStatus.UNAUTHORIZED,
      );
    }

    return true;
  }

  private validateToken(request: Request): string | undefined {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return request.headers['authorization'];
  }
}
